/***************************************************************************
 * 
 * Copyright (c) 2011 Baidu.com, Inc. All Rights Reserved
 * common.h,v 1.0 2012-08-17 11:31 yelu01 
 * 
 **************************************************************************/
 
 
 
/**
 * @file mutex.h
 * @author yelu01(yelu01@baidu.com)
 * @date 2012-08-21 10:08
 * @version 1.0 
 * @brief mutex class.
 *  
 **/

#pragma once

#include <pthread.h>
#include "check_macro.h"

class mutex_t
{
public:
	mutex_t()
	{
		CHECK_EQ_ZERO(pthread_mutex_init(&_mu, NULL), exit(1), "failed to create mutex.");
	};
	~mutex_t()
	{
		CHECK_EQ_ZERO(pthread_mutex_destroy(&_mu), return, "failed to destroy mutex.");
	}
	int lock()
	{
		CHECK_EQ_ZERO(pthread_mutex_lock(&_mu), return -1, "failed to lock mutex.");
		return 0;
	}
	int unlock()
	{
		CHECK_EQ_ZERO(pthread_mutex_unlock(&_mu), return -1, "failed to unlock mutex.");
		return 0;
	}
private:
	pthread_mutex_t _mu;
	// No copy
	mutex_t(const mutex_t&);
	void operator=(const mutex_t&);
};

class auto_mutex_t
{
public:
	auto_mutex_t(mutex_t& mutex):
		_mutex(mutex)
	{
		_mutex.lock();
	}
	~auto_mutex_t()
	{
		_mutex.unlock();
	}
private:
	mutex_t& _mutex;
	// No copy
	auto_mutex_t(const auto_mutex_t&);
	void operator=(const auto_mutex_t&);
};
